package com.java.springcloud.feign;

import com.google.gson.Gson;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import lombok.Data;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.PostMapping;

/**
 * @Author zhangtao
 * @create 2022/3/7 18:34
 */
@FeignClient(name = "test", path = "/", url = "http://10.218.223.247:9090", configuration = FeignService.FormSupportConfig.class)
public interface FeignService {

    /**
     * 令牌
     *
     * @param data
     */
    @PostMapping(value = "/atm-web/test")
    void token(SsoTokenRequest data);


    class FormSupportConfig {
        @Autowired
        private ObjectFactory<HttpMessageConverters> messageConverters;

        @Bean
        public Encoder feignFormEncoder() {
            return new SpringFormEncoder(new SpringEncoder(messageConverters));
        }

        @Bean("myInterceptor")
        public RequestInterceptor getRequestInterceptor() {
            return new MyClientInterceptor();
        }

        @Bean
        Logger.Level feignLoggerLevel() {
            return Logger.Level.FULL;
        }
    }

    class MyClientInterceptor implements RequestInterceptor {
        @Override
        public void apply(RequestTemplate requestTemplate) {
            // 通过template获取到请求体（已经被转成json）
            String jsonBody = new String(requestTemplate.body());
            SsoTokenRequest request = new Gson().fromJson(jsonBody, SsoTokenRequest.class);
            if (request != null) {
                String code = request.getCode();
                request.setUrl(requestTemplate.url());
                requestTemplate.body(new Gson().toJson(request));
            }
        }
    }

    @Data
    class SsoTokenRequest {
        private String code;
        private String url;
    }

}
